package com.haole.ecommercepay.common;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.ContentType;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson.JSONObject;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

/**
 * @author haole
 * 网络请求相关
 */
public class HttpUtils {

    public static final String API_URL_PREFIX = "https://api.mch.weixin.qq.com";

    public static HttpResponse v3HttpExecute(String method,String urlSuffix,String appName,
                                                  String mchId, String mchSerialNo, String wechatSerialNo, String body,String mchPrivateKeyPath,
                                                  File file) {
        // 构建 Authorization
        String authorization = SignUtils.authorization(method, urlSuffix, mchId, mchSerialNo, body, mchPrivateKeyPath);

        if ("GET".equalsIgnoreCase(method)) {
            return doGet(API_URL_PREFIX.concat(urlSuffix), authorization, wechatSerialNo, appName);
        } else if ("POST".equalsIgnoreCase(method)) {
            return doPost(API_URL_PREFIX.concat(urlSuffix), authorization, wechatSerialNo, body,appName);
        } else if ("DELETE".equalsIgnoreCase(method)) {
            return doDelete(API_URL_PREFIX.concat(urlSuffix), authorization, wechatSerialNo, body,appName);
        } else {
            return doMedia(API_URL_PREFIX.concat(urlSuffix), authorization, wechatSerialNo, body, file,appName);
        }
    }

    private static HttpResponse doGet(String url,String authorization,String serialNo,String appName) {
        return HttpRequest.get(url)
                .addHeaders(commonHeaders(authorization, serialNo, appName))
                .execute();
    }

    private static HttpResponse doPost(String url,String authorization,String serialNo,String jsonData,String appName) {
        return HttpRequest.post(url)
                .addHeaders(commonHeaders(authorization, serialNo, appName))
                .body(jsonData)
                .execute();
    }

    private static HttpResponse doDelete(String url, String authorization, String serialNo, String jsonData, String appName) {
        return HttpRequest.delete(url)
                .addHeaders(commonHeaders(authorization, serialNo, appName))
                .body(jsonData)
                .execute();
    }

    private static HttpResponse doMedia(String url, String authorization, String serialNo, String jsonData, File file,String appName) {
        return HttpRequest.post(url)
                .addHeaders(mediaHeaders(authorization, serialNo,appName))
                .form("file", file)
                .form("meta", jsonData)
                .execute();
    }

    /**
     * 基础heads
     * @param authorization
     * @param appName
     * @return
     */
    private static Map<String, String> baseHeaders(String authorization,String appName) {
        String userAgent = String.format(
                "WeChatPay-IJPay-HttpClient (%s) Java",
                appName);

        Map<String, String> headers = new HashMap<>(4);
        headers.put("Accept", ContentType.JSON.toString());
        headers.put("Authorization", authorization);
        headers.put("User-Agent", userAgent);
        return headers;
    }

    /**
     * 普通heads
     * @param authorization
     * @param serialNo
     * @param appName
     * @return
     */
    private static Map<String, String> commonHeaders(String authorization,String serialNo,String appName) {
        Map<String, String> headers = baseHeaders(authorization,appName);
        headers.put("Content-Type", ContentType.JSON.toString());
        if (StrUtil.isNotEmpty(serialNo)) {
            headers.put("Wechatpay-Serial", serialNo);
        }
        return headers;
    }

    /**
     * 上传素材的heads
     * @param authorization
     * @param serialNo
     * @param appName
     * @return
     */
    private static Map<String, String> mediaHeaders(String authorization,String serialNo,String appName) {
        Map<String, String> headers = baseHeaders(authorization,appName);
        headers.put("Content-Type", "multipart/form-data;boundary=\"boundary\"");
        if (StrUtil.isNotEmpty(serialNo)) {
            headers.put("Wechatpay-Serial", serialNo);
        }
        return headers;
    }

    public static JSONObject httpResult(HttpResponse response, String wechatPubKeyPath) {
        int status = response.getStatus();
        JSONObject result =  new JSONObject();
        //204 - No Content 处理成功，无返回Body
        if (status != 204) {
            result = JSONObject.parseObject(response.body());
        }
        //签名验证成功
        if (SignUtils.v3VerifyRSA(response,wechatPubKeyPath)) {
            result.put("requestStatus",response.getStatus());
            //微信支付给每个接收到的请求分配了一个唯一标示。请求的唯一标示包含在应答的HTTP头Request-Id中。当需要微信支付帮助时，请提供请求的唯一标示，以便我们更快的定位到具体的请求。
            result.put("Request-ID",response.headers().get("Request-ID").get(0));
            System.out.println("Request-ID："+response.headers().get("Request-ID").get(0));
            return result;
            //签名验证失败
        } else {
            result.put("status",1001);
            result.put("message","验签失败");
            return result;
        }
    }
}
